//
//  M_SettingVC.swift
//  letuofu
//
//  Created by WH-JS on 2020/1/9.
//  Copyright © 2020 WH-JS. All rights reserved.
//

import UIKit
import AVKit

class M_SettingVC: BaseViewControllerWithHeader,UINavigationControllerDelegate,UIImagePickerControllerDelegate {
    let sizeLab = UILabel()
    let imageView = UIImageView()
    let labRenzheng = UILabel()
    var financeData : [String:Any?]?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        getUserInfo()
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    func getUserInfo() {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? ""]
        API.request(url: .M_GetUserInfo, params: params) { (result) in
            if result.success {
               if let dl = result.data?.getDictionary("data") {
                if var urlstring = dl.getString("headPic"),urlstring.count > 0 {
                       urlstring = (IMG_HOST_URL2+urlstring).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
                       let url = URL(string: urlstring)
                       self.imageView.sd_setImage(with:url)
                   }else{
                       self.imageView.image = UIImage.init(named: "touxiang_97")
                   }
               }
            }else{
//                let popup = PopupSureBox(title: result.errMsg ?? "登录失败，请重新登录", sureText: "确定")
//                popup.show(vc: UIViewController.topMostController() ?? self)
//                popup.onSureButtonClick = {
//                    //确定执行
//                }
            }
        }
    }
    
    func getFinancialAccount(callback: @escaping ([String:Any?]) -> Void) {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? ""]
        API.request(url: .F_GetFinancialAccount, params: params) { (result) in
            if result.success {
               if let dl = result.data?.getDictionary("data") {
                LocalStorage.saveDic(dl, forKey: FINANCIAL_ACCUNT)
                callback(dl)
               }
            }else{
            }
        }
    }
    
    
    func logoutAction(callback: @escaping ([String:Any?],Bool) -> Void) {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? ""]
        API.request(url: .L_Logout, params: params) { (result) in
            if result.success {
               if let dl = result.data?.getDictionary("data") {
                callback(dl,result.success)
               }
            }else{
                callback([:],result.success)
            }
        }
    }
    
    func updateUserHeaderPic(_ img:UIImage) {
        if let imgString = UIImageAndBase64.imageToBase64String(imageOri: img, headerSign: true) {
            let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                        "headerPic":imgString]
            API.request(url: .M_UpdateUserHeaderPic, params: params) { (result) in
                if result.success {
                   if let dl = result.data?.getDictionary("data") {
                    if var urlstring = dl.getString("headPic"),urlstring.count > 0 {
                        urlstring = (IMG_HOST_URL2+urlstring).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
                        let url = URL(string: urlstring)
                        self.imageView.sd_setImage(with:url)
                    }else{
                        self.imageView.image = UIImage.init(named: "touxiang_97")
                    }
                   }
                }else{
                    let popup = PopupSureBox(title: result.errMsg ?? "更新失败", sureText: "确定")
                    popup.show(vc: UIViewController.topMostController() ?? self)
                    popup.onSureButtonClick = {
                        //确定执行
                    }
                }
            }
        }
    }
    
}

// MARK: UI
extension M_SettingVC {
    func setupUI() {
        safeView.backgroundColor = .xF2F2F2
        headView.backgroundColor = .white
        headTitle.text = "设置"
        
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

        
        var bgview = scrollView.drawView { (make) in
            make.top.equalToSuperview().offset(10)
            make.left.right.equalToSuperview()
            make.height.equalTo(51.5)
        }
        bgview.backgroundColor = .white
        bgview.drawImage(imageView: imageView,named: "touxiang_97") { (make) in
            make.width.equalTo(41.5)
            make.right.equalToSuperview().offset(-5)
            make.top.equalToSuperview().offset(5)
            make.bottom.equalToSuperview().offset(-5)
        }
        imageView.contentMode = .scaleAspectFit
        imageView.clipsToBounds = true
        imageView.layer.cornerRadius = 20.75
        
        bgview.drawLabel(text: "我的头像", fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-80)
        }
        bgview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(headImgViewTap(tap:))))
        
        bgview = scrollView.drawView { (make) in
            make.top.equalTo(bgview.snp.bottom).offset(10)
            make.left.right.equalToSuperview()
            make.height.equalTo(51.5)
        }
        bgview.backgroundColor = .white
        bgview.drawLabel(text: "个人信息", fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-80)
        }
        bgview.drawImage(named: "youjiantou_55") { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-10)
        }
        bgview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(gerenxinxiTap(tap:))))
        
        //画横线
        var line = bgview.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        //审核版本不显示
        if false {
//        if !(LocalStorage.getBool(forKey: ISINREVIEW) ?? false) {
                    bgview = scrollView.drawView { (make) in
                        make.top.equalTo(bgview.snp.bottom).offset(10)
                        make.left.right.equalToSuperview()
                        make.height.equalTo(51.5)
                    }
                    bgview.backgroundColor = .white
                    bgview.drawLabel(text: "实名认证", fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
                        make.centerY.equalToSuperview()
                        make.left.equalToSuperview().offset(10)
            //            make.right.equalToSuperview().offset(-80)
                    }
                    bgview.drawImage(named: "youjiantou_55") { (make) in
                        make.centerY.equalToSuperview()
                        make.right.equalToSuperview().offset(-10)
                    }
                    bgview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(shimingrenzheng(tap:))))
                    bgview.drawLabel(label: labRenzheng,text: "未认证", fontSize: 12, textColor: .x333333) { (make) in
                        make.centerY.equalToSuperview()
            //            make.left.equalToSuperview().offset(10)
                        make.right.equalToSuperview().offset(-20)
                    }
                    getFinancialAccount(callback: { (data) in
                        self.labRenzheng.text = "已认证"
                        self.financeData = data
                    })
                    
                    //画横线
                    line = bgview.drawView { (make) in
                        make.left.equalToSuperview().offset(10)
                        make.right.equalToSuperview().offset(-10)
                        make.bottom.equalToSuperview()
                        make.height.equalTo(1)
                    }
                    line.backgroundColor = .xF2F2F2
                    
                    bgview = scrollView.drawView { (make) in
                        make.top.equalTo(bgview.snp.bottom).offset(10)
                        make.left.right.equalToSuperview()
                        make.height.equalTo(51.5)
                    }
                    bgview.backgroundColor = .white
                    bgview.drawLabel(text: "借记卡", fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
                        make.centerY.equalToSuperview()
                        make.left.equalToSuperview().offset(10)
                        make.right.equalToSuperview().offset(-80)
                    }
                    bgview.drawImage(named: "youjiantou_55") { (make) in
                        make.centerY.equalToSuperview()
                        make.right.equalToSuperview().offset(-10)
                    }
                    bgview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(jiejikaTap(tap:))))
                    
                    //画横线
                    line = bgview.drawView { (make) in
                        make.left.equalToSuperview().offset(10)
                        make.right.equalToSuperview().offset(-10)
                        make.bottom.equalToSuperview()
                        make.height.equalTo(1)
                    }
                    line.backgroundColor = .xF2F2F2
        }
        
        bgview = scrollView.drawView { (make) in
            make.top.equalTo(bgview.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(51.5)
        }
        bgview.backgroundColor = .white
        bgview.drawLabel(text: "我的地址", fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-80)
        }
        bgview.drawImage(named: "youjiantou_55") { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-10)
        }
        bgview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(wodedizhiTap(tap:))))
        
        //画横线
        line = bgview.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        
        bgview = scrollView.drawView { (make) in
            make.top.equalTo(bgview.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(51.5)
        }
        bgview.backgroundColor = .white
        bgview.drawLabel(text: "修改密码", fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-80)
        }
        bgview.drawImage(named: "youjiantou_55") { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-10)
        }
        bgview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(xiugaimimaTap(tap:))))
        
        //画横线
        line = bgview.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        bgview = scrollView.drawView { (make) in
            make.top.equalTo(bgview.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(51.5)
        }
        bgview.backgroundColor = .white
        bgview.drawLabel(text: "设置默认商城", fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-80)
        }
        bgview.drawImage(named: "youjiantou_55") { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-10)
        }
        bgview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(shezhishangchengTap(tap:))))
        
        //画横线
        line = bgview.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        bgview = scrollView.drawView { (make) in
            make.top.equalTo(bgview.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(51.5)
        }
        bgview.backgroundColor = .white
        bgview.drawLabel(text: "清除缓存数据", fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-80)
        }
        bgview.drawImage(named: "youjiantou_55") { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-10)
        }
        bgview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(qingchuhuancunTap(tap:))))
        let size = String(format:"%.2f",CachesManager.defule.fileSizeOfCache())//取两位小数
        bgview.drawLabel(label: sizeLab,text: size + "M", fontSize: 12, textColor: .x666666) { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-25)
        }
        
        bgview = scrollView.drawView { (make) in
            make.top.equalTo(bgview.snp.bottom).offset(10)
            make.left.right.equalToSuperview()
            make.height.equalTo(51.5)
        }
        bgview.backgroundColor = .white
        bgview.drawLabel(text: "注销账号", fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-80)
        }
        bgview.drawImage(named: "youjiantou_55") { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-10)
        }
        bgview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(zhuxiaoTap(tap:))))
        
        bgview = scrollView.drawView { (make) in
            make.top.equalTo(bgview.snp.bottom).offset(10)
            make.left.right.equalToSuperview()
            make.height.equalTo(51.5)
        }
        bgview.backgroundColor = .white
        bgview.drawLabel(text: "退出当前账号", fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-80)
        }
        bgview.drawImage(named: "youjiantou_55") { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-10)
        }
        bgview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tuichuTap(tap:))))
        
        let btn = scrollView.drawButton(title: "切换商城", titleColor: .white, fontSize: 15) { (make) in
            make.top.equalTo(bgview.snp.bottom).offset(30)
            make.centerX.equalToSuperview()
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-30)
            make.height.equalTo(35)
        }
        btn.backgroundColor = .xFC4C02
        btn.layer.cornerRadius = 7
        btn.addTarget(self, action: #selector(_changeButtonClick(button:)), for: .touchUpInside)
        
        scrollView.bottomEqualTo(btn, offset: 50)
    }
}

// MARK: 事件
extension M_SettingVC {
    @objc func headImgViewTap(tap:UITapGestureRecognizer){
        let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
            actionSheet.addAction(UIAlertAction(
                title: "拍照" , style: .default, handler: {(_) in
                    AppAuthority.cameraPermissions(authorizedBlock: {
                        mainQueueAsync {
                            self.goCamera()
                        }
                    }, deniedBlock: {
                        let popup = PopupSureBox(title: "您关闭了相机功能，请在设置中打开", sureText: "确定")
                        popup.show(vc: UIViewController.topMostController() ?? self)
                        popup.onSureButtonClick = {
                            //确定执行
                        }
                    })
            }))
            actionSheet.addAction(UIAlertAction(
                title: "相册" , style: .default, handler: {(_) in
                    AppAuthority.photoAlbumPermissions(authorizedBlock: {
                        mainQueueAsync {
                            self.goImage()
                        }
                    }, deniedBlock: {
                        let popup = PopupSureBox(title: "您关闭了相册功能，请在设置中打开", sureText: "确定")
                        popup.show(vc: UIViewController.topMostController() ?? self)
                        popup.onSureButtonClick = {
                            //确定执行
                        }
                    })
            }))
        actionSheet.addAction(UIAlertAction(title: "取消", style: .cancel))
        UIViewController.topMostController()?.present(actionSheet, animated: true)
        actionSheet.pruneNegativeWidthConstraints()
    }
    
    @objc func shimingrenzheng(tap:UITapGestureRecognizer){
        if financeData != nil {
            let vc = F_UserInfoVC()
            vc.financeInfo = financeData!
            pushViewController(vc)
        }
        else {
            let vc = F_UserAuthenticationVC()
            pushViewController(vc)
        }
    }
    
    @objc func jiejikaTap(tap:UITapGestureRecognizer){
        if labRenzheng.text == "已认证" {
            let vc = F_BankCardListVC()
            pushViewController(vc)
        }
        else {
            let popup = PopupSureBox(title: "您还没有实名认证，请先进行实名认证", infoText: "", sureText: "确定")
            popup.show(vc: UIViewController.topMostController() ?? self)
            popup.onSureButtonClick = {
                //确定执行
            }
        }
    }
    
    @objc func gerenxinxiTap(tap:UITapGestureRecognizer){
        let vc = M_UserInfoVC()
        pushViewController(vc)
    }
    @objc func wodedizhiTap(tap:UITapGestureRecognizer){
        let vc = M_MyAddressListVC()
        pushViewController(vc)
        vc.headTitle.text = "我的地址"
    }
    @objc func shezhishangchengTap(tap:UITapGestureRecognizer){
        let vc = StoreListVC(switchMallOnSelected: false)
        vc.isSetting = true
        pushViewController(vc)
    }
    @objc func xiugaimimaTap(tap:UITapGestureRecognizer){
        let vc = L_Phone_PwdVC()
        pushViewController(vc)
    }
    @objc func qingchuhuancunTap(tap:UITapGestureRecognizer){
        
        let popup = PopupConfirmBox(info: "确定清除缓存", title: "")
        popup.show(vc: UIViewController.topMostController() ?? self)
        popup.onSureButtonClick = {
            //确定执行
            CachesManager.defule.clearCache()
            let size = String(format:"%.2f",CachesManager.defule.fileSizeOfCache())//取两位小数
            self.sizeLab.text = size + "M"
            let popup = PopupBox(infoText: "清除缓存成功")
            popup.show(vc: UIViewController.topMostController() ?? self)
        }
    }
    @objc func tuichuTap(tap:UITapGestureRecognizer){
        let popup = PopupConfirmBox(info: "确定退出当前账号", title: "")
        popup.show(vc: UIViewController.topMostController() ?? self)
        popup.onSureButtonClick = {
            self.logoutAction(callback: {_,_ in
                
            })
            LocalStorage.saveString("", forKey: LOGIN_PASSWORD)
            //确定执行
            self.popViewControllerToTop()
        }
    }
    
    @objc func zhuxiaoTap(tap:UITapGestureRecognizer){
        let popup = PopupSureBox(title: "请与人事联系处理，谢谢", sureText: "确定")
        popup.show(vc: UIViewController.topMostController() ?? self)
        popup.onSureButtonClick = {
            //确定执行
        }
    }
    
    @objc func _changeButtonClick(button:Button){
        let vc = StoreListVC(switchMallOnSelected: false)
        vc.isSetting = true
        vc.isChange = true
        pushViewController(vc)
    }
    
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    // 去拍照
    func goCamera(){
                    
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            let  cameraPicker = UIImagePickerController()
            cameraPicker.delegate = self
            cameraPicker.allowsEditing = true
            cameraPicker.sourceType = .camera
            //在需要的地方present出来
            cameraPicker.modalPresentationStyle = .fullScreen
            UIViewController.topMostController()?.present(cameraPicker, animated: true, completion: nil)
        } else {
            
            print("不支持拍照")
            
        }
    }
    
    /// 去相册
    func goImage(){
        let photoPicker =  UIImagePickerController()
        photoPicker.delegate = self
        photoPicker.allowsEditing = true
        photoPicker.sourceType = .savedPhotosAlbum
        //在需要的地方present出来
        photoPicker.modalPresentationStyle = .fullScreen
        UIViewController.topMostController()?.present(photoPicker, animated: true, completion: nil)
    }
      ///UIImagePickerControllerDelegate
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            print("获得照片============= \(info)")
            
            let image : UIImage = info[UIImagePickerController.InfoKey.editedImage] as! UIImage

            //上传，成功则显示设置的照片
            updateUserHeaderPic(image)

            UIViewController.topMostController()?.dismiss(animated: true, completion: nil)
        }
}

//缓存整理
class CachesManager {
      static let defule = CachesManager()
      let fileManager = FileManager.default

      func fileSizeOfCache()-> Double {
          
          // 获取Caches目录路径和目录下所有文件
       guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first,let files = fileManager.subpaths(atPath: cachePath) else{
              return 0
          }
          
          //枚举出所有文件，计算文件大小
          var folderSize :Double = 0
          for file in files {
              // 路径拼接
            let path = cachePath +  ("/\(file)")
              // 计算缓存大小
              folderSize  += fileSizeAtPath(path:path)
          }
          
          return folderSize/(1024*1024)
          
      }
      
      func fileSizeAtPath(path:String) -> Double{
          
          if fileManager.fileExists(atPath: path) {
           
            let attr = try! fileManager.attributesOfItem(atPath: path)
              return Double(attr[FileAttributeKey.size] as! UInt64)
          }
          return 0
          
      }

     func clearCache() {
      
        guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first,
              let files = fileManager.subpaths(atPath: cachePath) else { return }
        
        for file in files {
            if let fname = anyToString(file) {
                let path = cachePath + "/" + fname
                if fileManager.fileExists(atPath: path) {
                    
                    do {
                        try fileManager.removeItem(atPath: path)
                    } catch  {
                         print(error.localizedDescription)
                    }
                }
            }
        }
    }
    
}
